public class Answer2 {
    //单词搜索
    //https://www.nowcoder.com/practice/987f2981769048abaf6180ed63266bb2?tpId=196&tqId=39583&ru=/exam/oj


    public static void main(String[] args) {
        String[] board={"XYZE","SFZS","XDEE"};
        String word="XYZZED";
        boolean b = exist(board,word);
        System.out.println(b);
    }


    static int[] dx = new int[] {1, -1, 0, 0};
    static int[] dy = new int[] {0, 0, 1, -1};
    static int n=0;
    static int m=0;
    static boolean[][] dp;

    public static boolean exist (String[] board, String word) {
        // write code here
        n = board.length; m = board[0].length();
        dp = new boolean[n][m];
        boolean b = false;

        char[] words = word.toCharArray();

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (!dp[i][j] && board[i].charAt(j) == words[0]) {
                    dp[i][j] = true;
                    b = dfs(board, words,  i, j, 1);
                    if (!b) dp[i][j] = false;
                    else return true;
                }
            }
        }

        return false;
    }

    public static boolean dfs(String[] board, char[] words, int i, int j,
                       int x) {
        n = board.length;m = board[0].length();
        boolean b = false;
        for (int a = 0; a < 4; a++) {
            if ( i + dx[a] < n && i + dx[a] >= 0 &&
                    j + dy[a] < m && j + dy[a] >= 0 &&
                    !dp[i + dx[a]][j + dy[a]] && board[i + dx[a]].charAt(j + dy[a]) == words[x]) {
                dp[i + dx[a]][j + dy[a]] = true;
                if (x == words.length-1) return true;
                b = dfs(board, words, i + dx[a], j + dy[a], x + 1);
                if (!b)  dp[i + dx[a]][j + dy[a]] = false;
                else return true;
            }
        }
        return false;
    }

















    /*int m, n;
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};
    boolean[][] vis;
    char[] word;
    public boolean exist (String[] board, String _word) {
        m = board.length;
        n = board[0].length();
        vis = new boolean[m][n];
        word = _word.toCharArray();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i].charAt(j) == word[0]) {
                    if (dfs(board, i, j, 0) == true) return true;
                }
            }
        }
        return false;
    }
    public boolean dfs(String[] board, int i, int j, int pos) {
        if (pos == word.length - 1) {
            return true;
        }

        vis[i][j] = true;
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] &&
                    board[x].charAt(y) == word[pos + 1]) {
                if (dfs(board, x, y, pos + 1)) return true;
            }
        }
        vis[i][j] = false;

        return false;
    }*/
 }

